package rpc

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

// http 对外交互
func (m *RoadsRequest) http(timeOut time.Duration) (*RoadsResponse, error) {
	fmt.Println("开始连接三方服务！")
	payload := bytes.NewReader(m.Body)
	client := &http.Client{
		Timeout: timeOut,
	}
	request, err := http.NewRequestWithContext(context.Background(), m.Method, m.Url, payload)
	if err != nil {
		fmt.Println("err1:", err.Error())
		return &RoadsResponse{Status: http.StatusBadRequest, Header: nil, Body: nil}, err
	}
	for k, v := range m.Header {
		request.Header.Add(k, v)
	}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println("err2:", err.Error())
		return &RoadsResponse{Status: http.StatusBadGateway, Header: nil, Body: nil}, err
	}
	header := make(map[string]string)
	for k, strings := range resp.Header {
		header[k] = strings[0]
	}
	if err != nil {
		if resp != nil {
			fmt.Println("err3:", err.Error())
			return &RoadsResponse{Status: int64(resp.StatusCode), Header: header, Body: nil}, err
		} else {
			fmt.Println("err4:", err.Error())
			return &RoadsResponse{Status: http.StatusBadGateway, Header: nil, Body: nil}, err
		}
	}
	defer func() {
		if resp != nil {
			_ = resp.Body.Close()
		}
	}()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("err5:", err.Error())
		return &RoadsResponse{Status: int64(resp.StatusCode), Header: header, Body: nil}, err
	}
	return &RoadsResponse{Status: int64(resp.StatusCode), Header: header, Body: body}, err
}
